from models import User, sql_session
from hashlib import md5


def encrypt(password):
    salt_head = 'Chain For Perls'
    salt_end = 'Should we replace Perls for Pearls?'
    m = md5()
    code = salt_head + password + salt_end
    for i in range(16):
        m.update(code)
        code = m.hexdigest()
    return code[0:20]


def create_user(username, password):
    result = sql_session.query(User).filter(User.username == username).count()
    if result > 0:
        return '_username_existed'
    classified = encrypt(password)
    user = User(username=username, password=classified, success=0, failure=0, score=100)
    sql_session.add(user)
    sql_session.commit()


def authenticate(username, password):
    result = sql_session.query(User).filter(User.username == username)
    if not result.count():
        return None
    user = result.all()[0]
    encrypted = encrypt(password)
    if encrypted == user.password:
        return user
    else:
        return None


def set_password(user, password):
    if not isinstance(user, User):
        return '_invalid_user'
    classified = encrypt(password)
    user.password = classified
    sql_session.add(user)
    sql_session.commit()


def get_history(username):
    result = sql_session.query(User).filter(User.username == username)
    if not result.count():
        return None
    user = result.all()[0]
    return user.success, user.failure, user.score


def set_history(user, **kwargs):
    if not isinstance(user, User):
        return '_invalid_user'
    if kwargs.get('success'):
        user.success = kwargs['success']
    if kwargs.get('failure'):
        user.failure = kwargs['failure']
    if kwargs.get('score'):
        user.failure = kwargs['score']
    sql_session.add(user)
    sql_session.commit()


def resign_update_history(username, partner):
    user_history = get_history(username)
    set_history(username, failure=user_history[1] + 1)
    partner_history = get_history(partner)
    set_history(partner, success=partner_history[0] + 1)

if __name__ == '__main__':
    # pass
    create_user('yichya', '1234')
    user = authenticate('yichya', '1234')
    set_password(user, 'abcd')
    user = authenticate('yichya', 'abcd')
    set_history(user, success=1)
    user = authenticate('yichya', 'abcd')
    print (user.username, user.success)
